﻿define(function (require) {
    var logger = require('modules/logger');
    var router = require('plugins/router');
    var hub;

    var hubService = {
        usersOnlineMsg: ko.observable(null),
        init: function () {
            var self = this;
            var cn = $.hubConnection();
            hub = cn.createHubProxy('order');
            hub.on('addedInfo', function (notification) {
                notifyView(notification);
                addedInfo(notification);
            });
            hub.on('deletedInfo', function (notification) {
                notifyView(notification);
                deletedInfo(notification);
            });
            hub.on('newUserConnected', function (notification) {
                newUserConnected(notification);
            });
            hub.on('usersOnline', function (message) {
                self.usersOnlineMsg(message);
            });
            hub.on('removeMessage', function () {
                self.usersOnlineMsg(null);
            });
            cn.start().done(function () {
                hub.invoke('start');
                logger.info('Connected');
            });
        },
        connectToOrderView: function (orderId) {
            hub.invoke('ConnectToOrderView', orderId);
        },
        disconnectFromOrderView: function (orderId) {
            hub.invoke('DisconnectToOrderView', orderId);
        }
    };

    function notifyView(notification) {
        if (typeof router.activeItem().onNotification !== 'undefined') {
            router.activeItem().onNotification(notification);
        }
    }

    function addedInfo(notification) {
        logger.info(notification.Message);
    }

    function deletedInfo(notification) {
        logger.warning(notification.Message);
    }

    function newUserConnected(notification) {
        logger.info(notification);
    }

    return hubService;
});